﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.ISerivces;
using DWF.Studio.ScriptEngine.IPC.Msg;
using DWF.Studio.ScriptEngine.IPC.NamedPipe;
using DWF.Studio.Share.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DWF.Studio.Services
{
    internal class EngineIPCService : IEngineIPCService
    {
        private static readonly EngineIPCService _engineIPCService = new EngineIPCService();

        private const string _pipeNamePrefix = "RemoteEnginePipe";
        /// <summary>
        /// 工程管理类引用
        /// </summary>
        public static EngineIPCService Instance
        {
            get
            {
                return _engineIPCService;
            }
        }

        private NamedPipeService _namedPipeService = null;

        private EngineIPCService()
        {
            var guid = Guid.NewGuid().ToString("N");
            _namedPipeService = new NamedPipeService($"{_pipeNamePrefix}_{guid}");
            _namedPipeService.UnhandleError += (e) =>
            {
                LogHelper.Error(e);
            };
        }

        public string GetPipeName()
        {
            return _namedPipeService.PipeName;
        }

        public void Start()
        {
            _namedPipeService.Start();
        }

        public void Stop()
        {
            _namedPipeService.Stop();
        }

        public void Send(DownwardMsg msg)
        {
            _namedPipeService.Send(msg);
        }

        public void AddReceiveAction(Action<UpwardMsg> action)
        {
            _namedPipeService.ReceiveMessage += action;
        }

        public void RemoveReceiveAction(Action<UpwardMsg> action)
        {
            _namedPipeService.ReceiveMessage -= action;
        }
    }
}
